package assetprocess;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Scanner;


import database.Jdbcmysql;

import structure.AssetNode;
import structure.Relationship;
/**
 * 程式資訊摘要 : 擷取XML文件資訊特徵
 * 版本資訊:1.0
 * 程式設計人員姓名: 朱聖池
 */

public class AssetPreprocess{
	private String solution_ID = null;
	private String solution_Name = null;
	private String solution_Version = null;
	private HashMap<String, AssetNode> graph_Node = new HashMap<String, AssetNode>();
	private ArrayList<Relationship> graph_Edge = new ArrayList<Relationship>();
	private HashMap<String,HashMap<String,ArrayList<Relationship>>> headNode_Edge_list = 
			new HashMap<String,HashMap<String,ArrayList<Relationship>>>();

	
	/**
	 * 分析及擷取XML文件資訊特徵
	 * @param filepath
	 * @throws IOException
	 */
	public void setAssetInformation(String filepath) throws IOException{
        try{
        	Scanner input = new Scanner(new File(filepath));
            // 建立儲存Asset的物件
            AssetNode asset = new AssetNode();
            AssetNode lastasset = new AssetNode();
            HashMap<String,ArrayList<Relationship>> SolutionMap= new HashMap<String,ArrayList<Relationship>>() ;
            ArrayList<Relationship> head_feature = new ArrayList<Relationship>() ;
            
            while(input.hasNext()){
            	
            	String line = input.nextLine().trim();
            	if (line.startsWith("<asset assetID")) {
                    int beginIndex = line.indexOf('"') + 1;
                    int endIndex = line.lastIndexOf('"');
                    asset.setAssetID(line.substring(beginIndex, endIndex));
                }
            	if (line.startsWith("<assetName>")) {
                    int beginIndex = line.indexOf('>') + 1;
                    int endIndex = line.lastIndexOf('/') - 1;
                    asset.setAssetName(line.substring(beginIndex, endIndex));
                }
            	if (line.startsWith("<version>")) {
                    int beginIndex = line.indexOf('>') + 1;
                    int endIndex = line.lastIndexOf('/') - 1;
                    asset.setVersion(line.substring(beginIndex, endIndex));
                }
                if (line.startsWith("<assetTypeName>")) {
                	int beginIndex = line.indexOf('>') + 1;
	                int endIndex = line.lastIndexOf('/') - 1;
	                asset.setAssetLayer(line.substring(beginIndex, endIndex));
	                asset.setAssetTypeName(line.substring(beginIndex, endIndex));//
	                if(line.contains("Solution")){
		                asset.setAssetLayerType(0);
		                // 特別記錄 Solution方案的ID
		                solution_ID = asset.getAssetID();
		                solution_Name = asset.getAssetName();
		                solution_Version = asset.getVersion();
	                }
                }
                if (line.startsWith("<shortDescription>")) {//
                	//取得智產描述
                    int beginIndex = line.indexOf('>') + 1;
                    int endIndex = line.lastIndexOf('/') - 1;
                    if(endIndex > 0 ){
                    	asset.setShortDescription(line.substring(beginIndex, endIndex));
                    }
                    else{
                    	String extraline = line.substring(beginIndex, line.length()) ;
                    	String next =  input.nextLine().trim() ;
                    	
                    	while(next.lastIndexOf('/')<0){
                    		extraline = extraline + next.substring(0,next.length()) ;
                    		next = input.nextLine().trim() ;
                    	}
                    	if(next.lastIndexOf('/')>0){
                    		int second_end = next.lastIndexOf('/') - 1 ;
                        	extraline = extraline + next.substring(0,second_end) ;
                    	}
                    	asset.setShortDescription(extraline);
                    }

                    
                }
                // 給予標註此 專利是在第幾層
                if (line.startsWith("<layer>")) {
                    String[] sTemp = getLayer(line).split(",");
                    asset.setAssetLayer(sTemp[0]);
                    asset.setAssetLayerType(Integer.parseInt(sTemp[1]));
                }
                if (line.startsWith("<relations>")) {
                    while (input.hasNext()) {
                    	
                        Relationship relation = new Relationship();
                        relation.setHead(asset);
                        line = input.nextLine().trim();
                        //可能有多個relation
                        if(line.startsWith("<relation>")){
                        	while(input.hasNext()){
                        		line = input.nextLine().trim();
		                        if (line.startsWith("<relationType>")) {
		                            int beginIndex = line.indexOf('>') + 1;
		                            int endIndex = line.lastIndexOf('/') - 1;
		                            relation.setRelations(line.substring(beginIndex, endIndex));
		                        }
		                        if (line.startsWith("<associateAssetName>")) {
		                            int beginIndex = line.indexOf('>') + 1;
		                            int endIndex = line.lastIndexOf('/') - 1;
		                            lastasset.setAssetName(line.substring(beginIndex, endIndex));
		                        }
		                        if (line.startsWith("<associateAssetVersion>")) {
		                            int beginIndex = line.indexOf('>') + 1;
		                            int endIndex = line.lastIndexOf('/') - 1;
		                            lastasset.setVersion(line.substring(beginIndex, endIndex));
		                        }
		                        if (line.startsWith("<associateAssetID>")) {
		                            int beginIndex = line.indexOf('>') + 1;
		                            int endIndex = line.lastIndexOf('/') - 1;
		                            lastasset.setAssetID(line.substring(beginIndex, endIndex));
		                        }
		                        if (line.startsWith("</relation>")) {
		                        	relation.setTail(lastasset);
		                        	lastasset = new AssetNode();
		                        	//加入new Edge
		                        	graph_Edge.add(relation);
		                        	head_feature.add(relation);
		                            break;
		                        }
                        	}
                        }
                        if (line.startsWith("</relations>")) {
                        	SolutionMap.put(asset.getAssetID()+"_"+asset.getVersion(), head_feature) ;
                        	head_feature = new ArrayList<Relationship>() ;
                            break;
                        }
                    }
                }
                if (line.startsWith("</asset>")) {
                	updateAssetnode(asset.getAssetID()+"_"+asset.getVersion(),asset) ;
                	asset = new AssetNode();
                }
                
            }
            headNode_Edge_list.put(solution_ID+"_"+solution_Version, SolutionMap);
          
            //整份文件掃完將relation的點關係補足
            updateRelation();
            

        }catch (FileNotFoundException e){
            e.printStackTrace();
        }
		
	}

	/**
	 * 重設所有全域變數
	 */
	public void resetGolbal() {
		 solution_ID = null;
		 solution_Name = null;
		 graph_Node = new HashMap<String, AssetNode>();
		 graph_Edge = new ArrayList<Relationship>();
	}

	/**
     * 將取得的階層做文字的轉換
     * @param str
     * @return  String
     */
    private String getLayer(String str) {
        String LayerType = "";
        if (str.contains("Strategy")) {
            LayerType = "Strategy,1";
        } else if (str.contains("Operation")) {
            LayerType = "Operation,2";
        } else if (str.contains("Execution")) {
            LayerType = "Execution,3";
        } else if (str.contains("Implementation")) {
            LayerType = "Implementation,4";
        }
        return LayerType;
    }
    /**
     * 插入圖裡所有資訊(包含Asset,Relation,Solution)
     */
    public void insertDB() {
    	Jdbcmysql db = new Jdbcmysql();
        db.creatRelationsTable();
        db.creatSolutionTable();
        db.creatNodeTable();
        int count = 0 ;
        //插入node
        for(Entry<String, AssetNode> entry : graph_Node.entrySet()){
        	AssetNode tmp = entry.getValue();
        	db.insertNode(tmp.getAssetID(), tmp.getAssetName(), tmp.getAssetLayerType(), tmp.getVersion(), tmp.getAssetTypeName(), tmp.getShortDescription(), tmp.getGrpahID());
        	count++ ;
        }
        System.out.println("新增智產點"+count+"個成功");
        count = 0 ;
        //插入edge
        Iterator edge = graph_Edge.iterator();
        while(edge.hasNext()){
        	Relationship relations = (Relationship) edge.next();
        	AssetNode head = relations.getHead();
        	AssetNode Tail = relations.getTail();
        	
        	db.insertRelations(head.getGrpahID(), head.getAssetID(), head.getVersion()
        			, relations.getRelations(), Tail.getAssetID(), Tail.getVersion());
        	count++;
        	
        }
        System.out.println("新增特徵邊"+count+"條成功");
        //插入solution
        db.insertSolution(solution_ID+"_"+solution_Version,solution_Name);
        System.out.println(solution_Name+"　新增解決方案成功");
    }
    
	/**
	 * 更新智產點屬性(因為從SQL:relations table缺少部分屬性)
	 * @param id
	 * @param node
	 */
    private void updateAssetnode(String id, AssetNode node){
    	node.setGrpahID(solution_ID);
    	if(id!=null)
    		graph_Node.put(id, node);
    	
    	//writeDoc(id , node.getshortDescription());
    	//addDoc(id,node);
    }

	/**
     * 更新關係邊上點的資訊
     */
    private void updateRelation() {
    	ArrayList<Relationship> updateRelation = new ArrayList<Relationship>();
    	Iterator edge = graph_Edge.iterator();
    	while(edge.hasNext()){
    		Relationship relations = (Relationship) edge.next();
    		AssetNode h = relations.getHead();
    		AssetNode t = relations.getTail();
    		h = graph_Node.get(h.getAssetID()+"_"+h.getVersion());
    		t = graph_Node.get(t.getAssetID()+"_"+t.getVersion());
    		relations.setHead(h);
    		relations.setTail(t);
    		updateRelation.add(relations);
    	}
    	graph_Edge = updateRelation;
		
	}
	/**
	 * 回傳該XML的智產點
	 * @return HashMap<String, AssetNode>
	 */
    public HashMap<String, AssetNode> getNode(){
    	return graph_Node ;
    }
    /**
     * 回傳該XML的特徵邊
     * @return ArrayList<Relationship>
     */
    public ArrayList<Relationship> getEdge(){
    	return graph_Edge ;
    }
    /**
     * 回傳該XML 以key值為headNode的邊 table
     * @return HashMap<String, HashMap<String, ArrayList<Relationship>>>
     */
    public HashMap<String, HashMap<String, ArrayList<Relationship>>> getHead_Edge(){
    	return headNode_Edge_list ;
    }
    /**
     * 回傳soution id
     * @return String
     */
    public String getSolutionId(){
    	return solution_ID ;
    }
    /**
     * 回傳solution version
     * @return String
     */
    public String getSolutionVersion(){
    	return solution_Version ;
    }
}
